package com.can.core.advice;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Desription 后台管理切面
 * @Author can
 * @Date 2018/9/30
 * @Version 1.0
 */
//申明是个切面
@Aspect
//申明是个spring管理的bean
@Component
public class WebContollerAop {
    private final static Logger logger = LoggerFactory.getLogger(ValidateControllerAdvice.class);
    private final String[] specialUrl = new String[]{"/user/defaultKaptcha"};

    @Pointcut("execution( * com.can.controller..*(..))")
    public void controllerAspect(){

    }

    /**
     * 是否是特殊url，比如获取验证码，请求参数拿不到，会出错
     * @param url 需要验证的url
     * @return
     */
    private boolean isSpecialUrl(String url){
        if (StringUtils.isEmpty(url)) {
            return true;
        }
        for(int i = 0; ArrayUtils.isNotEmpty(specialUrl) && i < specialUrl.length; i++){
            if (StringUtils.isNotBlank(specialUrl[i]) && url.endsWith(specialUrl[i])) {
                return true;
            }
        }
        return false;
    }

    //请求method前打印内容
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //打印请求内容
        logger.info("===============请求内容===============");
        logger.info("请求地址:"+request.getRequestURL().toString());
        logger.info("请求方式:"+request.getMethod());
        logger.info("请求类方法:"+joinPoint.getSignature());
        if(!isSpecialUrl(request.getRequestURL().toString())){
            logger.info("请求类方法参数:"+ JSON.toJSONString(joinPoint.getArgs()));
        }

        logger.info("===============请求内容===============");
    }
    //在方法执行完结后打印返回内容
    @AfterReturning(returning = "o",pointcut = "controllerAspect()")
    public void methodAfterReturing(Object o ){
        logger.info("--------------返回内容----------------");
        logger.info("Response内容:"+ JSON.toJSONString(o));
        logger.info("--------------返回内容----------------");
    }
}
